package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.domain.SystemMenu;
import cn.wolfcode.wms.mapper.SystemMenuMapper;
import cn.wolfcode.wms.page.PageResult;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.ISystemMenuService;
import cn.wolfcode.wms.util.UserContext;
import cn.wolfcode.wms.vo.SystemMenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class SystemMenuServiceImpl implements ISystemMenuService {
    @Autowired
    private SystemMenuMapper mapper;

    public void save(SystemMenu systemMenu) {
        mapper.insert(systemMenu);
    }

    public void delete(long id) {
        mapper.deleteByPrimaryKey(id);
    }

    public void update(SystemMenu systemMenu) {
        mapper.updateByPrimaryKey(systemMenu);
    }

    public SystemMenu get(long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<SystemMenu> list() {
        return mapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int rows = mapper.queryForCount(qo);
        if (rows == 0) {
            return PageResult.empty(qo.getPageSize());
        }
        List<?> result = mapper.queryForList(qo);
        return new PageResult(result, rows, qo.getCurrentPage(), qo.getPageSize());
    }

    public void saveOrUpdate(SystemMenu systemMenu) {
        if (systemMenu.getId() != null) {
            mapper.updateByPrimaryKey(systemMenu);
        } else {
            mapper.insert(systemMenu);
        }
    }

    public List<SystemMenu> listAllparent(Long parentId) {
        List<SystemMenu> list = new ArrayList<>();
        SystemMenu parent = mapper.selectByPrimaryKey(parentId);
        while (parent != null) {
            list.add(parent);
            parent = parent.getParent();
        }
        Collections.reverse(list);
        return list;
    }

    public List<SystemMenuVo> loadTree(String parentSn) {
        Employee currentUser = UserContext.getCurrentUser();
        if (currentUser.isAdmin()) {
            return loadSystemMenuByParentSn(parentSn);
        }
        return loadSystemMenuByParentSnAndEmpId(parentSn, currentUser.getId());
    }

    private List<SystemMenuVo> loadSystemMenuByParentSnAndEmpId(String parentSn, Long empId) {
        return mapper.loadSystemMenuByParentSnAndEmpId(parentSn,empId);
    }

    private List<SystemMenuVo> loadSystemMenuByParentSn(String parentSn) {
        return mapper.loadSystemMenuByParentSn(parentSn);
    }

}
